package com.hmdp.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     * @return
     */
    public Result queryTypeList() {
        String key = RedisConstants.CACHE_SHOP_KEY + "type";
        //查看Redis是否有店铺类型
        String shopTypeList = stringRedisTemplate.opsForValue().get(key);

        //命中缓存
        if (shopTypeList != null){
            List<ShopType> typeList = JSONObject.parseArray(shopTypeList,ShopType.class);
            return Result.ok(typeList);
        }
        //没有命中则去数据库查询，之后写入Redis
        List<ShopType> typeList= query().orderByAsc("sort").list();

        //这里不能直接toString(),要转成json格式的String
        stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(typeList));
        if (typeList == null){
            return Result.fail("无数据，错误!");
        }
        return Result.ok(typeList);
    }
}
